'use strict';

const Service = require('egg').Service;

class PropertyService extends Service {
  async list(query = {}) {
    const {
      page = 1,
      pageSize = 12,
      keyword = '',
      city = '',
      priceMin,
      priceMax,
      areaMin,
      areaMax,
      sortField,
      sortOrder,
    } = query;

    const offset = (Number(page) - 1) * Number(pageSize);
    const limit = Number(pageSize);

    // 仅展示上架房源
    const wheres = ['status = ?'];
    const params = ['available'];

    if (keyword) {
      wheres.push('(title LIKE ? OR description LIKE ? OR address LIKE ?)');
      const like = `%${keyword}%`;
      params.push(like, like, like);
    }
    if (city) {
      wheres.push('city = ?');
      params.push(city);
    }
    if (priceMin !== undefined && priceMin !== '' && !isNaN(priceMin)) {
      wheres.push('price >= ?');
      params.push(Number(priceMin));
    }
    if (priceMax !== undefined && priceMax !== '' && !isNaN(priceMax)) {
      wheres.push('price <= ?');
      params.push(Number(priceMax));
    }
    if (areaMin !== undefined && areaMin !== '' && !isNaN(areaMin)) {
      wheres.push('area >= ?');
      params.push(Number(areaMin));
    }
    if (areaMax !== undefined && areaMax !== '' && !isNaN(areaMax)) {
      wheres.push('area <= ?');
      params.push(Number(areaMax));
    }

    // 排序白名单
    const sortFieldMap = {
      price: 'price',
      area: 'area',
      created_at: 'created_at',
    };
    const order = (String(sortOrder || '').toLowerCase() === 'asc') ? 'ASC' : 'DESC';
    const sortCol = sortFieldMap[sortField] || 'id';

    const whereSql = wheres.length ? ('WHERE ' + wheres.join(' AND ')) : '';
    const countSql = `SELECT COUNT(*) AS total FROM houses ${whereSql}`;
    const listSql = `
      SELECT id, title, price, area, address, city, district, images, created_at
      FROM houses
      ${whereSql}
      ORDER BY ${sortCol} ${order}
      LIMIT ? OFFSET ?
    `;

    // 统计
    const countRows = await this.app.mysql.query(countSql, params);
    const total = countRows?.[0]?.total || 0;

    // 列表
    const listParams = params.slice();
    listParams.push(limit, offset);
    const rows = await this.app.mysql.query(listSql, listParams);

    // 处理 cover
    const items = rows.map(r => {
      let cover = '';
      try {
        if (r.images) {
          const arr = JSON.parse(r.images);
          if (Array.isArray(arr) && arr.length) cover = arr[0];
        }
      } catch (_) {}
      return {
        id: r.id,
        title: r.title,
        price: Number(r.price),
        area: Number(r.area),
        address: r.address,
        city: r.city,
        district: r.district,
        cover,
        created_at: r.created_at,
      };
    });

    return { total, items };
  }

  async detail(id) {
    const sql = `
      SELECT h.*, u.username, u.phone as owner_phone
      FROM houses h
      LEFT JOIN users u ON h.user_id = u.id
      WHERE h.id = ? AND h.status IN ('available','rented','sold')
      LIMIT 1
    `;
    const rows = await this.app.mysql.query(sql, [Number(id)]);
    if (!rows || !rows.length) return null;

    const r = rows[0];
    let images = [];
    try {
      if (r.images) {
        const arr = JSON.parse(r.images);
        if (Array.isArray(arr)) images = arr;
      }
    } catch (_) {}
    return {
      id: r.id,
      title: r.title,
      description: r.description,
      price: Number(r.price),
      area: Number(r.area),
      address: r.address,
      city: r.city,
      district: r.district,
      room_type: r.room_type,
      bedrooms: r.bedrooms,
      living_rooms: r.living_rooms,
      bathrooms: r.bathrooms,
      status: r.status,
      images,
      user_id: r.user_id,
      owner_name: r.username,
      owner_phone: r.owner_phone,
      created_at: r.created_at,
      updated_at: r.updated_at,
    };
  }

  // 创建房源
  async create(data) {
    const {
      title,
      description,
      price,
      area,
      address,
      city,
      district,
      room_type,
      bedrooms,
      living_rooms,
      bathrooms,
      images,
      user_id
    } = data;

    // 参数验证
    if (!title || !price || !area || !address || !city || !district) {
      throw new Error('必填字段不能为空');
    }

    if (price <= 0 || area <= 0) {
      throw new Error('价格和面积必须大于0');
    }

    const result = await this.app.mysql.insert('houses', {
      title,
      description,
      price: Number(price),
      area: Number(area),
      address,
      city,
      district,
      room_type: room_type || 'apartment',
      bedrooms: bedrooms || 1,
      living_rooms: living_rooms || 1,
      bathrooms: bathrooms || 1,
      images: images ? JSON.stringify(images) : null,
      status: 'available',
      user_id,
      created_at: new Date(),
      updated_at: new Date()
    });

    return result;
  }

  // 更新房源
  async update(id, data) {
    const updateData = { ...data };
    updateData.updated_at = new Date();

    if (updateData.images) {
      updateData.images = JSON.stringify(updateData.images);
    }

    const result = await this.app.mysql.update('houses', updateData, {
      where: { id }
    });

    return result;
  }

  // 删除房源
  async delete(id) {
    const result = await this.app.mysql.delete('houses', { id });
    return result;
  }

  // 获取用户的房源列表
  async getUserProperties(userId, query = {}) {
    const { page = 1, pageSize = 10 } = query;
    const offset = (Number(page) - 1) * Number(pageSize);
    const limit = Number(pageSize);

    const sql = `
      SELECT * FROM houses 
      WHERE user_id = ? 
      ORDER BY created_at DESC 
      LIMIT ? OFFSET ?
    `;

    const countSql = `SELECT COUNT(*) AS total FROM houses WHERE user_id = ?`;

    const [rows, countRows] = await Promise.all([
      this.app.mysql.query(sql, [userId, limit, offset]),
      this.app.mysql.query(countSql, [userId])
    ]);

    const total = countRows?.[0]?.total || 0;

    const items = rows.map(r => {
      let images = [];
      try {
        if (r.images) {
          const arr = JSON.parse(r.images);
          if (Array.isArray(arr)) images = arr;
        }
      } catch (_) {}
      
      return {
        id: r.id,
        title: r.title,
        description: r.description,
        price: Number(r.price),
        area: Number(r.area),
        address: r.address,
        city: r.city,
        district: r.district,
        room_type: r.room_type,
        bedrooms: r.bedrooms,
        living_rooms: r.living_rooms,
        bathrooms: r.bathrooms,
        status: r.status,
        images,
        created_at: r.created_at,
        updated_at: r.updated_at
      };
    });

    return { total, items };
  }
}

module.exports = PropertyService;